package com.gr100.biz.api.order;

import com.gr100.biz.api.bo.MetaObject;
import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mysql.jdbc.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

/**
 * Created by james on 16/3/16.
 */
public class OrderModel {
    private static final Log logger = Log.getLog("UserModel");
    private static OrderModel ourInstance = new OrderModel();

    public static OrderModel me() {
        return ourInstance;
    }

    private OrderModel() {
    }


    DbPro api = Db.use("api");
    DbPro ec = Db.use("ec");
    DbPro erp = Db.use("erp");

    /**
     * 验证用户购物车内是否有商品
     * @param o
     * @return
     */
    public boolean checkExists(Order o){

        String uid = o.getUid();
        String sql = "";
        List<Record> list = null;

        sql = "select pid,psid,number from gr_user_cart a where a.checked = 1 and a.number > 0 and a.uid = '"+uid+"' and a.delflag = 0 ";
        list = ec.find(sql);

        if(list.size()>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 验证用户购物车内商品是否下架
     * @param o
     * @return
     */
    public boolean checkInvalid(Order o){
        String uid = o.getUid();

        String sql = "";
        List<Record> list = null;

        int t = 0;
        sql = "select pid,psid,number from gr_user_cart a where a.checked = 1 and a.number > 0 and a.uid = '"+uid+"' and a.delflag = 0 ";
        list = ec.find(sql);

        for(int i=0;i<list.size();i++){
            //判断商品是否下架
            int pid = Integer.parseInt(list.get(i).getStr("pid"));			//规格编号
            int psid = Integer.parseInt(list.get(i).getStr("psid"));			//规格编号

            List<Record> spec = ec.find("select 1 from gr_product a,gr_product_spec b where a.id = b.pid and a.status = 1 and b.status = 1 and b.pid = ? and b.id = ?",pid,psid);

            if(spec.size() == 0){
                t += 1;
            }
        }

        if(t == 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 验证商品库存是否充足
     * @param o
     * @return
     */
    public boolean checkInventory(Order o){

        String uid = o.getUid();
        String sql = "";
        List<Record> list = null;

        sql = "select pid,psid,number from gr_user_cart a where a.checked = 1 and a.number > 0 and a.uid = '"+uid+"' and a.delflag = 0 ";
        list = ec.find(sql);

        int t = 0;

        for(int i=0;i<list.size();i++){
            //判断商品库存是否充足
            int pid = Integer.parseInt(list.get(i).getStr("pid"));			//规格编号
            int psid = Integer.parseInt(list.get(i).getStr("psid"));			//规格编号
            int number = list.get(i).getInt("number");			//规格编号

            List<Record> spec = ec.find("select b.inventory from gr_product a,gr_product_spec b where a.id = b.pid and a.status = 1 and b.status = 1 and b.pid = ? and b.id = ?", pid, psid);

            if(spec.get(0).getInt("inventory") < number){
                t += 1;
            }
        }

        if(t == 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 验证订单原价是否正确
     * @param o
     * @return
     */
    public boolean checkAmount(Order o){

        String uid = o.getUid();
        String total = o.getTotal();

        String sql = "select IFNULL(sum(c.grprice*a.probability*a.number),0) price "
                + " from gr_user_cart a,gr_product b,gr_product_spec c "
                + " where a.pid = b.id "
                + " and a.psid = c.id "
                + " and b.id = c.pid "
                + " and a.checked = 1 "
                + " and a.delflag = 0 "
                + " and a.uid = '"+uid+"' ";
        List<Record> list = ec.find(sql);

        double yj = list.get(0).getDouble("price");

        DecimalFormat df=new DecimalFormat("0.00");

        String str1 = df.format(Double.valueOf(total))+"";
        String str2 = df.format(yj)+"";

        if(!str1.equals(str2)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 验证订单实付金额是否正确
     * @param o
     * @return
     */
    public boolean checkFinalAmount(Order o){

        String total = o.getTotal();
        String finalAmount = o.getFinalAmount();
        String par = o.getPar();
        String hdje = o.getgCoin();
        String expresscost = o.getExpresscost();
        String mjtitle = o.getmjtitle();
        String mjamount = o.getmjamount();

        String couponDiscountId = o.getcouponDiscountId();
        String couponDiscountPar = o.getcouponDiscountPar();

        int gCoinChecked = o.getgCoinChecked();

        String zkje = "0";

            if(gCoinChecked == 0){
                hdje = "0";
            }

            if("/".equals(mjtitle)){
                mjamount = "0";
            }

            NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(2);

            if(gCoinChecked == 0){
                hdje = "0";
            }

            if(!"0".equals(couponDiscountId) && !StringUtils.isNullOrEmpty(couponDiscountId)){
                //获取折扣金额
                Double b1= Double.valueOf(total)*(1 - Double.valueOf(couponDiscountPar));
                zkje = nf.format(b1);
            }

            //实付金额 ＝ 总价 － 运费 － 优惠券 － 活动余额 － 满减余额 － 折扣余额
            double dou_total = Double.valueOf(total);
            double dou_expresscost = Double.valueOf(expresscost);
            double dou_par = Double.valueOf(par);
            double dou_hdje = Double.valueOf(hdje);
            double dou_mjamount = Double.valueOf(mjamount);
            double dou_zkje = Double.valueOf(zkje);
            double dou_fa = Double.valueOf(finalAmount);

            double je = dou_total + dou_expresscost - dou_par - dou_hdje - dou_mjamount - dou_zkje;

            if(je < 0){
                je = 0;
            }

            DecimalFormat df=new DecimalFormat("0.00");

            String str1 = df.format(je)+"";
            String str2 = df.format(dou_fa)+"";

            if(!str1.equals(str2)){
                return false;
            }

        return true;
    }

    /**
     * 验证用户定时券
     * @param o
     * @return
     */
    public boolean checkUserTimingCouponId(Order o){

        int UserTimingCouponId = o.getUserTimingCouponId();
        String TimingPrice = o.getTimingPrice();
        String uid = o.getUid();
        String sql = "";
        List<Record> list = null;

        sql = "select a.* from gr_timeservice_usercoupons a,gr_timeservice_coupons b " +
                " where a.cid = b.id " +
                " and a.used = 0 " +
                " and a.uid = '"+uid+"' " +
                " and a.id = "+UserTimingCouponId+" " +
                " and b.price = "+TimingPrice ;
        list = ec.find(sql);

        if(list.size()>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 验证用户余额是否正确
     * @param o
     * @return
     */
    public boolean checkUserBalance(Order o){

        String uid = o.getUid();
        String yeAmount = o.getyeAmount();

        List<Record> users = api.find("select ifnull(balance,0) balance from gr_login_info where id = ? ", uid);
        String balance = users.get(0).get("balance").toString();

        DecimalFormat df=new DecimalFormat("0.00");
        String balance_str = df.format(Double.valueOf(balance))+"";
        String yeAmount_str = df.format(Double.valueOf(yeAmount))+"";

        if(Double.valueOf(balance_str) < Double.valueOf(yeAmount_str)){
            return false;
        }

        return true;
    }

    /**
     * 验证会员定时券
     * @param o
     * @return
     */
    public boolean checkMemberTimingCouponId(Order o){

        int MemberTimingCouponId = o.getMemberTimingCouponId();
        String TimingPrice = o.getTimingPrice();
        String uid = o.getUid();
        String sql = "";
        List<Record> list = null;

        sql = "select a.* from gr_timeservice_membercoupons a,gr_timeservice_coupons b " +
                " where a.cid = b.id " +
                " and a.count > 0 " +
                " and a.uid = '"+uid+"' " +
                " and a.id = "+MemberTimingCouponId+" " +
                " and b.price = "+TimingPrice ;
        list = ec.find(sql);

        if(list.size()>0){
            return true;
        }else{
            return false;
        }
    }

    public static boolean isHave(List<Record> list,int pid){
      /*此方法有两个参数，第一个是要查找的字符串数组，第二个是要查找的字符或字符串
       * */
        for(int i=0;i<list.size();i++){
            if(list.get(i).getInt("pro_id") == pid){//循环查找字符串数组中的每个字符串中是否包含所有查找的内容
                return true;//查找到了就返回真，不在继续查询
            }
        }
        return false;//没找到返回false
    }

    /**
     * 验证优惠券是否正确
     * @param o
     * @return
     */
    public boolean checkCoupon(Order o){

        String uid = o.getUid();

        String couponId = o.getCouponId();
        String par  = o.getPar();

        if(!StringUtils.isNullOrEmpty(couponId) && !"0".equals(couponId) && !"null".equals(couponId)){

            String sql = " select b.reduce "
                    + " from gr_user_coupon a,gr_coupons b "
                    + " where a.cid = b.id and a.id = '"+couponId+"'"
                    + " and used = 0 and a.uid = '"+uid+"' ";
            List<Record> list = ec.find(sql);

            if(list.size() > 0){
                double a = Double.valueOf(par);
                double b = list.get(0).getDouble("reduce");
                BigDecimal val1 = new BigDecimal(a);
                BigDecimal val2 = new BigDecimal(b);

                if (val1.compareTo(val2) != 0) {
                    return false;
                }
            }else{
                return false;
            }
        }

        return true;
    }

    /**
     * 验证折扣优惠券是否正确
     * @param o
     * @return
     */
    public boolean checkCouponDiscount(Order o){
        String uid = o.getUid();

        String couponDiscountId = o.getcouponDiscountId();
        String couponDiscountPar  = o.getcouponDiscountPar();

        if(!StringUtils.isNullOrEmpty(couponDiscountId) && !"0".equals(couponDiscountId) && !"null".equals(couponDiscountId) ){

            String sql = " select b.reduce "
                    + " from gr_user_coupon a,gr_coupons b "
                    + " where a.cid = b.id and a.id = '"+couponDiscountId+"'"
                    + " and used = 0 and a.uid = '"+uid+"' ";
            List<Record> list = ec.find(sql);

            if(list.size() > 0){
                double a = Double.valueOf(couponDiscountPar);
                double b = list.get(0).getDouble("reduce");
                BigDecimal val1 = new BigDecimal(a);
                BigDecimal val2 = new BigDecimal(b);

                if (val1.compareTo(val2) != 0) {
                    return false;
                }
            }else{
                return false;
            }
        }

        return true;
    }

    /**
     * 验证活动余额是否正确
     * @param o
     * @return
     */
    public boolean checkgCoin(Order o){

        double finalGCoin = 0;              //最终可以使用的果币
        double disc = 0;                //折扣金额
        String uid = o.getUid();
        String gCoin  = o.getgCoin();
        String total = o.getTotal();

        //订单金额 ＝ 原始订单金额 － 会员商品折扣金额 － 优惠券减金额 － 活动余额
        double ddje = Double.valueOf(total);

        //获取当前用户账户上的活动余额
        List<Record> list = api.find("select a.gCoin from gr_login_info a where a.id =?", uid);
        double userGCoin = list.get(0).getDouble("gCoin");

        if(ddje >= 300){
            disc = ddje * 0.4;
        }else if(ddje >= 150){
            disc = ddje * 0.3;
        }else if(ddje >= 50){
            disc = ddje * 0.2;
        }else if(ddje >= 20){
            disc = ddje * 0.15;
        }else if(ddje >= 10){
            disc = ddje * 0.1;
        }else{
            disc = 0;
        }

        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        disc = Double.valueOf(nf.format(disc));

        //如果账户上的活动余额小于折扣金额，则以账户上的活动余额为准
        if(userGCoin > disc){
            finalGCoin = disc;
        }else{
            finalGCoin = userGCoin;
        }

        DecimalFormat df=new DecimalFormat("0.00");

        String str1 = df.format(Double.valueOf(gCoin))+"";
        String str2 = df.format(finalGCoin)+"";

        if(!str1.equals(str2)){
            return false;
        }

        return true;
    }

    /**
     * 删除用户购物车商品
     * @param o
     * @return
     */
    public boolean delCart (Order o){
        String uid = o.getUid();

        boolean t = true;

        //ec.update("delete from gr_user_cart where uid = ? and checked = 1 ",uid);
        String sjc10 = Long.toString(System.currentTimeMillis()).substring(0, 10);

        ec.update("update gr_user_cart set delflag = 1,updateAt = ? where uid = ? and checked = 1 and delflag = 0 ",sjc10,uid);

        return t;
    }

    /**
     * 生成订单
     * @param o
     * @return
     */
    @Before(Tx.class)
    public int save(Order o){

        String sjc = o.getSJC();                                    //时间戳
        sjc = sjc.substring(0,10);
        String orderid = o.getOrderId();
        String groupNo = o.getGroupNo();
        String type = o.getType();                                  //订单类型
        double total = Double.valueOf(o.getTotal());                //订单原价
        double finalAmount = Double.valueOf(o.getFinalAmount());    //订单实际金额
        String uid = o.getUid();                                    //用户编号
        String toName = o.getToName();                              //收货人
        String toPhone = o.getToPhone();                            //联系电话
        String toStreet = o.getToStreet();                          //收货地址
        String couponId = o.getCouponId();                          //优惠券编号
        String remark = o.getRemark();                              //描述
        double par = Double.valueOf(o.getPar());                                    //优惠金额
        int gCoinChecked = o.getgCoinChecked();                     //是否使用活动余额
        double gCoin = Double.valueOf(o.getgCoin());                                //活动余额
        int yeAmountChecked = o.getyeAmountChecked();                     //是否使用余额
        double yeAmount = Double.valueOf(o.getyeAmount());                                //余额
        String status = "1000";                                     //订单状态
        int areaId = o.getAreaId();
        int shopId = o.getShopId();
        double lng = o.getLng();
        double lat = o.getLat();
        String confidence = o.getConfidence();
        String toProvince = o.getToProvince();
        String toCity = o.getToCity();
        String bookdate = o.getBookdate();
        double expresscost = Double.valueOf(o.getExpresscost());
        String expressname = o.getExpressname();
        String expresstype = o.getExpresstype();
        String deliveryTime = o.getDeliveryTime();
        int UserTimingCouponId = o.getUserTimingCouponId();
        int MemberTimingCouponId = o.getMemberTimingCouponId();
        String TimingPrice = o.getTimingPrice();
        String level = o.getlevel();
        String mjtitle = o.getmjtitle();

        if(gCoinChecked == 0){
            gCoin = 0;
        }

        //把信息插入到订单表
        this.saveOrder(orderid, groupNo, uid, areaId, shopId, sjc, type, total, finalAmount, status, bookdate, expresscost, expressname, expresstype, deliveryTime, UserTimingCouponId, MemberTimingCouponId, TimingPrice, yeAmountChecked, yeAmount);

        //把信息插入到订单组表
        this.saveOrderGroup(groupNo, orderid, sjc, uid, total, finalAmount, toProvince, toCity, toName, toPhone, toStreet, remark, couponId, par, gCoin, lng, lat, level, confidence, expresscost, expressname, expresstype, deliveryTime, UserTimingCouponId, MemberTimingCouponId, TimingPrice, mjtitle, yeAmountChecked, yeAmount);

        return 1;
    }

    /**
     * 保存订单及商品
     * @param
     * @return
     */
    public int saveOrder(String orderid,String groupNo,String uid,int areaId,int shopId,String sjc,String type,double total,double finalAmount,String status,String bookdate,double expresscost,String expressname,String expresstype,String deliveryTime,int UserTimingCouponId,int MemberTimingCouponId,String TimingPrice,int yeAmountChecked,double yeAmount){

        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);

        String strgoods = "";
        int givePoint = 0;

        List<Record> cart_list = null;

        String ordersql = " select a.pid,a.psid,a.number,b.name proname,c.name spname,c.point,c.grprice*a.probability grprice,b.picurlarray "
                + " from gr_user_cart a,gr_product b,gr_product_spec c "
                + " where a.pid = b.id "
                + " and a.psid = c.id "
                + " and b.id = c.pid "
                + " and a.number > 0 "
                + " and a.checked = 1 "
                + " and b.status = 1 "
                + " and c.status = 1 "
                + " and c.inventory > 0 "
                + " and a.delflag = 0 "
                + " and a.uid = ?";
        cart_list = ec.find(ordersql, uid);

        //判断是否为预售商品
        String yssql = "select b.pro_id from gr_act_title a,gr_act_pro_relations b " +
                "where a.id = b.act_id " +
                "and b.delflag = 0 " +
                "and a.delflag = 0 " +
                "and a.status = 1 " +
                "and a.code = 'yushou'";
        List<Record> yslist = ec.find(yssql);

        String yspids = ",";
        if(yslist.size() > 0){
            for(int y=0;y<yslist.size();y++){
                yspids += yslist.get(y).getInt("pro_id") + ",";
            }
        }

        int ys_flag = yspids.indexOf("," + cart_list.get(0).getStr("pid") + ",");
        if(ys_flag == -1){
            //判断是否为福利商品
            String flsql = "select b.pro_id from gr_act_title a,gr_act_pro_relations b " +
                    "where a.id = b.act_id " +
                    "and b.delflag = 0 " +
                    "and a.delflag = 0 " +
                    "and a.status = 1 " +
                    "and a.code = 'fuli'";
            List<Record> fllist = ec.find(flsql);

            String flpids = ",";
            if(fllist.size() > 0){
                for(int f=0;f<fllist.size();f++){
                    flpids += fllist.get(f).getInt("pro_id") + ",";
                }
            }
            int fl_flag = flpids.indexOf("," + cart_list.get(0).getStr("pid")+",");

            if(fl_flag == -1){
                //判断是否为必抢商品
                String bqsql = "select b.pro_id from gr_act_title a,gr_act_pro_relations b " +
                        "where a.id = b.act_id " +
                        "and b.delflag = 0 " +
                        "and a.delflag = 0 " +
                        "and a.status = 1 " +
                        "and a.code = 'mrbq'";
                List<Record> bqlist = ec.find(bqsql);

                String bqpids = ",";
                if(bqlist.size() > 0){
                    for(int b=0;b<bqlist.size();b++){
                        bqpids += bqlist.get(b).getInt("pro_id") + ",";
                    }
                }
                int bq_flag = bqpids.indexOf("," + cart_list.get(0).getStr("pid")+",");

                if(bq_flag == -1){
                    type = "0";
                }else{
                    type = "15";
                }
            }else{
                type = "14";
            }
        }else{
            type = "5";
        }

        strgoods = "";

        for(int i=0;i<cart_list.size();i++){
            int pid = Integer.parseInt(cart_list.get(i).getStr("pid"));			    //商品编号
            int psid = Integer.parseInt(cart_list.get(i).getStr("psid"));			//规格编号
            int number = cart_list.get(i).getInt("number");		                    //购买件数
            String proname = cart_list.get(i).getStr("proname");			        //商品名称
            String spname = cart_list.get(i).getStr("spname");			            //规格名称
            int point = cart_list.get(i).getInt("point");		                    //商品积分
            double price = cart_list.get(i).getDouble("grprice");                   //商品价格
            double totalprice = price * number;									    //总价  商品价格 * 购买件数

            strgoods += proname+"("+spname+")/"+totalprice+"元"+number+"份;";		//商品信息
            givePoint += point * number;											//赠送积分

            String picurlarray = cart_list.get(i).getStr("picurlarray");

            String picurl = picurlarray.replace("[","").replace("]", "").replace("\"", "");

            int length = picurl.indexOf(",");

            if(length == -1){
                picurl = picurl;
            }else{
                picurl = picurl.substring(0,length);
            }

            Record goods = new Record();
            goods.set("orderid", orderid);
            goods.set("pid", pid);
            goods.set("specid", psid);
            goods.set("price", price);
            goods.set("cartnum", number);
            goods.set("point", point);
            goods.set("totalprice", totalprice);
            goods.set("proname", proname);
            goods.set("spname", spname);
            goods.set("picurl", picurl);
            goods.set("createAt", sjc);
            goods.set("updateAt", sjc);
            ec.save("gr_final_order_goods", goods);
        }

        Record order = new Record();
        order.set("orderid", orderid);
        order.set("groupNo", groupNo);

        //如果是单独活动商品订单（1~3天送达）,需要特殊处理下 该订单由 正常订单变成预售订单 type = 5
        if("0".equals(type) && "1~3天送达".equals(expresstype)){
            type = "5";
        }

        order.set("type", type);
        order.set("amount", total);
        order.set("finalAmount", finalAmount);
        order.set("receivableAmount", finalAmount);
        if(yeAmountChecked == 1){
            order.set("yeAmount", yeAmount);
        }
        order.set("areaId", areaId);
        order.set("shopId", shopId);
        order.set("status", status);
        order.set("goods", strgoods);
        order.set("givePoint", givePoint);
        order.set("bookdate", bookdate);
        order.set("deliveryTime", deliveryTime);
        order.set("expresscost", expresscost);
        order.set("expressname", expressname);
        order.set("expresstype", expresstype);

        order.set("userTimingCouponId", UserTimingCouponId);
        order.set("memberTimingCouponId", MemberTimingCouponId);
        order.set("timingPrice", TimingPrice);

        order.set("cancelTime",Integer.parseInt(sjc)+(30*60));
        order.set("createAt", sjc);
        order.set("updateAt", sjc);
        ec.save("gr_final_order", order);

        return 1;
    }

    /**
     * 保存订单组
     * @param
     * @return
     */
    public int saveOrderGroup(String groupNo,String orderid,String sjc,String uid,double total,double finalAmount,String toProvince,String toCity,String toName,String toPhone,String toStreet,String remark,String couponId,double par,double gCoin,double lng,double lat,String level,String confidence,double expresscost,String expressname,String expresstype,String deliveryTime,int UserTimingCouponId,int MemberTimingCouponId,String TimingPrice,String mjtitle,int yeAmountChecked,double yeAmount){
        Record ordergroup = new Record();

        ordergroup.set("groupNo", groupNo);
        ordergroup.set("uid", uid);
        ordergroup.set("amount", total);
        ordergroup.set("finalAmount", finalAmount);

        String tips ="";
        if(!"/".equals(mjtitle)){
            tips = " (系统提示:该订单享受满减活动:"+mjtitle+")";
        }

        ordergroup.set("toProvince", toProvince);
        ordergroup.set("toCity", toCity);
        ordergroup.set("toName", toName);
        ordergroup.set("toPhone", toPhone);
        ordergroup.set("toStreet", toStreet);
        ordergroup.set("remark", remark+tips);
        ordergroup.set("couponId", couponId);
        ordergroup.set("toLng", lng);
        ordergroup.set("toLat", lat);
        ordergroup.set("toLevel", level);
        ordergroup.set("confidence", confidence);
        ordergroup.set("coordinateId", "0");
        ordergroup.set("expresscost", expresscost);
        ordergroup.set("expressname", expressname);
        ordergroup.set("expresstype", expresstype);
        ordergroup.set("deliveryTime", deliveryTime);

        ordergroup.set("userTimingCouponId", UserTimingCouponId);
        ordergroup.set("memberTimingCouponId", MemberTimingCouponId);
        ordergroup.set("timingPrice", TimingPrice);

        ordergroup.set("createAt", sjc);
        ordergroup.set("updateAt", sjc);
        ec.save("gr_final_order_group", ordergroup);

        String batchsql = "insert into gr_order_pay(oid,way,count,createAt,updateAt) values(?,?,?,?,?)";
        ec.batch(batchsql, new Object[][]{{groupNo, "原价", total, sjc, sjc}, {groupNo, "实付金额", finalAmount, sjc, sjc}, {groupNo, "优惠券", par, sjc, sjc}, {groupNo, "活动余额", gCoin, sjc, sjc}, {groupNo, "会员折扣", 0, sjc, sjc}, {groupNo, "运费", expresscost, sjc, sjc}}, 1000);


        Record log = new Record();
        log.set("dataId", orderid);
        log.set("type", "用户操作");
        log.set("uid", uid);
        log.set("remark", "用户创建订单");
        log.set("createdate", sjc);
        log.set("createAt", sjc);
        log.set("updateAt", sjc);
        ec.save("gr_operate_log", log);

        //如果勾选了余额支付，并且余额 = 实付金额 ，则订单创建并且支付成功
        String sjc10 = Long.toString(System.currentTimeMillis()).substring(0, 10);

        DecimalFormat df=new DecimalFormat("0.00");
        String finalAmount_str = df.format(Double.valueOf(finalAmount))+"";
        String yeAmount_str = df.format(Double.valueOf(yeAmount))+"";

        if(yeAmountChecked == 1 && finalAmount_str.equals(yeAmount_str)){

            Record pay = new Record();
            pay.set("oid", groupNo);
            pay.set("way", "余额支付");
            pay.set("count", yeAmount);
            pay.set("createAt", sjc10);
            pay.set("updateAt", sjc10);
            ec.save("gr_order_pay", pay);

            String sql = "SELECT aa.oid,SUM(yj) yj,SUM(yhq) yhq,SUM(hdye) hdye FROM ( " +
                    "SELECT " +
                    "a.oid," +
                    "CASE WHEN a.way = '原价' THEN a.count ELSE 0 END yj," +
                    "CASE WHEN a.way = '优惠券' THEN a.count ELSE 0 END yhq," +
                    "CASE WHEN a.way = '活动余额' THEN a.count ELSE 0 END hdye " +
                    "FROM gr_order_pay a " +
                    "WHERE a.oid = '"+groupNo+"' ) aa " +
                    "GROUP BY aa.oid";
            List<Record> p = ec.find(sql);

            double yj = p.get(0).getDouble("yj");           //原价
            double yhq = p.get(0).getDouble("yhq");         //优惠券
            double hdye = p.get(0).getDouble("hdye");       //活动余额

            String payDetails = "余额支付:"+yeAmount+"元;(原价:"+yj+"元;";
            if(yhq>0){
                payDetails += "优惠券抵扣:"+yhq+"元;";
            }
            if(hdye>0){
                payDetails += "活动余额:"+hdye+"元;";
            }
            payDetails += ")";

            ec.update("update gr_final_order_group set payway = '余额支付',payTime=?,payDetails=? where groupNo = ?",sjc10,payDetails,groupNo);
            ec.update("update gr_final_order set status = 2000 where groupNo = ?",groupNo);

            Record operateLog = new Record();
            operateLog.set("dataId", orderid);
            operateLog.set("type", "用户操作");
            operateLog.set("uid", uid);
            operateLog.set("remark", "用户支付成功");
            operateLog.set("createdate", sjc10);
            operateLog.set("createAt", sjc10);
            operateLog.set("updateAt", sjc10);
            ec.save("gr_operate_log", operateLog);

            //如果地址的可信度为100分，则订单状态为自动审核
            List<Record> LBSAUTOVIA = ec.find("SELECT a.value FROM gr_config a WHERE a.name = 'LBSAUTOVIA'");

            if(LBSAUTOVIA.size() == 1 && "".equals(LBSAUTOVIA.get(0).getStr("value")) && "100".equals(confidence)){
                List<Record> group = api.find("select a.confidence,a.expresstype,FROM_UNIXTIME(a.deliveryTime) deliveryTime from gr_final_order_group a where a.groupNo = ?", orderid);

                String deliveryTime_unix = group.get(0).getStr("deliveryTime");

                ec.update("update gr_final_order set status = 2500,approvaldate = ?,approvaluid=1 where groupNo = ?",sjc,groupNo);

                Record autoLog1 = new Record();
                autoLog1.set("dataId", orderid);
                autoLog1.set("type", "订单");
                autoLog1.set("uid", uid);
                autoLog1.set("remark", "系统自动审核通过");
                autoLog1.set("createdate", sjc10);
                autoLog1.set("createAt", sjc10);
                autoLog1.set("updateAt", sjc10);
                ec.save("gr_operate_log", autoLog1);

                Record autoLog2 = new Record();
                autoLog2.set("dataId", orderid);
                autoLog2.set("type", "订单");
                autoLog2.set("uid", uid);
                autoLog2.set("remark", "订单物流方式:"+expresstype+",送达时间："+deliveryTime_unix+"");
                autoLog2.set("createdate", sjc10);
                autoLog2.set("createAt", sjc10);
                autoLog2.set("updateAt", sjc10);
                ec.save("gr_operate_log", autoLog2);

            }
        }else if(yeAmountChecked == 1 && finalAmount > yeAmount){
            Record pay = new Record();
            pay.set("oid", groupNo);
            pay.set("way", "余额支付");
            pay.set("count", yeAmount);
            pay.set("createAt", sjc10);
            pay.set("updateAt", sjc10);
            ec.save("gr_order_pay", pay);
        }

        return 1;
    }

    /**
     * 减少用户余额
     * @param
     * @return
     */
    @Before(Tx.class)
    public int lessenBalance(String uid,double amount,String content){
        Record record = new Record();

        List<Record> users = api.find("select ifnull(balance,0) balance from gr_login_info where id = ? ",uid);

        double beforebalance = Double.valueOf(users.get(0).get("balance").toString());
        double afterbalance = beforebalance - amount;

        record.set("uid", uid);
        record.set("newbalance", amount);
        record.set("beforebalance", beforebalance);
        record.set("afterbalance", afterbalance);
        record.set("content", content);
        record.set("createAt", System.currentTimeMillis());
        record.set("updateAt", System.currentTimeMillis());

        ec.save("gr_user_money", record);

        //更新用户表的实时积分
        api.update("update gr_login_info set balance = ? where id = ?", afterbalance, uid);

        return 1;
    }

    /**
     * 减少用户活动余额
     * @param
     * @return
     */
    @Before(Tx.class)
    public int lessengCoin(String uid,double amount,String content){

        Record record = new Record();

        String fsql = "select ifnull(gCoin,0) gCoin from gr_login_info where id = '"+uid+"' ";
        List<Record> users = api.find(fsql);


        double beforebalance = Double.valueOf(users.get(0).get("gCoin").toString());
        double afterbalance = beforebalance - amount;

        record.set("uid", uid);
        record.set("newbalance", amount);
        record.set("beforebalance", beforebalance);
        record.set("afterbalance", afterbalance);
        record.set("content", content);
        record.set("createAt", System.currentTimeMillis());
        record.set("updateAt", System.currentTimeMillis());

        ec.save("gr_gcoinflow", record);

        //更新用户表的实时积分
        api.update("update gr_login_info set gCoin = ? where id = ?", afterbalance, uid);

        return 1;
    }

    /**
     * 减少用户余额
     * @param
     * @return
     */
    @Before(Tx.class)
    public int lessengAmount(String uid,double amount,String content){

        Record money = new Record();

        String fsql = "select ifnull(balance,0) balance from gr_login_info where id = '"+uid+"' ";
        List<Record> users = api.find(fsql);


        double beforebalance = Double.valueOf(users.get(0).get("balance").toString());
        double afterbalance = beforebalance - amount;

        String sjc = Long.toString(System.currentTimeMillis()).substring(0, 10);

        money.set("uid", uid);
        money.set("newbalance", amount);
        money.set("beforebalance", beforebalance);
        money.set("afterbalance", afterbalance);
        money.set("content", content);
        money.set("createAt", sjc);
        money.set("updateAt", sjc);

        ec.save("gr_user_money", money);

        //更新用户表的实时积分
        api.update("update gr_login_info set balance = ? where id = ?", afterbalance, uid);

        return 1;
    }

    /**
     * 更新优惠券使用状态
     * @param
     * @return
     */
    @Before(Tx.class)
    public int updateCouponId(Order o){

        String sjc = o.getSJC();
        String couponId = o.getCouponId();
        String uid = o.getUid();

        return ec.update("update gr_user_coupon set used = 1,useddate = ? where id = ? and uid = ? ", sjc, couponId, uid);
    }

    /**
     * 更新折扣优惠券使用状态
     * @param
     * @return
     */
    @Before(Tx.class)
    public int updateDiscountCouponId(Order o){

        String sjc = o.getSJC();
        String couponId = o.getcouponDiscountId();
        String uid = o.getUid();

        return ec.update("update gr_user_coupon set used = 1,useddate = ? where id = ? and uid = ? ", sjc, couponId, uid);
    }

    /**
     * 更新用户定时券使用状态
     * @param
     * @return
     */
    @Before(Tx.class)
    public int updateUserCouponId(Order o){

        String sjc = o.getSJC();
        int UserTimingCouponId = o.getUserTimingCouponId();
        String uid = o.getUid();

        String sql = "update gr_timeservice_usercoupons set used = 1,updateAt = "+sjc+" where id = "+UserTimingCouponId+" and uid = "+uid+" and used = 0 ";
        logger.info(sql);

        return ec.update(sql);
    }

    /**
     * 更新会员定时券使用状态
     * @param
     * @return
     */
    @Before(Tx.class)
    public int updateMemberCouponId(Order o){

        String sjc = o.getSJC();
        int MemberTimingCouponId = o.getMemberTimingCouponId();
        String uid = o.getUid();

        String sql = "update gr_timeservice_membercoupons set count = count - 1,updateAt = "+sjc+" where id = "+MemberTimingCouponId+" and uid = "+uid+" and count > 0 ";
        logger.info(sql);

        return ec.update(sql);
    }

    /**
     * 更新商品库存
     * @param
     * @return
     */
    @Before(Tx.class)
    public int minusInventory(Order o){

        String uid = o.getUid();
        List<Record> list = null;

        list = ec.find("select pid,psid,number from gr_user_cart a where a.checked = 1 and a.number > 0 and a.delflag = 0 and a.uid = ?",uid);

        for(int i=0;i<list.size();i++){
            int pid = Integer.parseInt(list.get(i).getStr("pid"));			//规格编号
            int psid = Integer.parseInt(list.get(i).getStr("psid"));		//规格编号
            int number = list.get(i).getInt("number");			            //商品数量
            ec.update("update gr_product_spec set inventory  = inventory - "+number+" where pid = ? and id = ? ", pid, psid);
        }

        return 1;
    }
}
